package com.gyc.simple.sysuser.controller;

import com.gyc.simple.common.util.JwtUtils;
import com.gyc.simple.common.util.RedisUtils;
import com.gyc.simple.common.vo.ResponseType;
import com.gyc.simple.common.vo.User;
import com.gyc.simple.sysuser.entity.base.IUser;
import com.gyc.simple.sysuser.service.SysUserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

    @Autowired
    private SysUserService  sysUserService;
    @PostMapping("/login")
    public ResponseType login(@RequestBody IUser iUser){
        ResponseType responseType = new ResponseType();
        if (StringUtils.isEmpty(iUser.getIuLname()) || StringUtils.isEmpty(iUser.getIuPassword())) {
            responseType.setRespMsg("用户名或密码不能为空!");
            return responseType;
        }

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken(iUser.getIuLname(),iUser.getIuPassword());
        try {
            subject.login(token);
            responseType.setStatus(true);
            String jwt = RedisUtils.get("jwt_"+iUser.getIuLname());
            if(jwt!=null){
                responseType.setData(jwt);
            }else{
                IUser user = sysUserService.getUserByLoginName(iUser.getIuLname());
                responseType.setData(JwtUtils.createTokenWithClaim(new User(user.getIuId(),user.getIuLname())));
            }
            return responseType;
        }catch (LockedAccountException lae) {
            token.clear();
            responseType.setRespMsg("用户已经被锁定不能登录，请与管理员联系！");
            return responseType;
        } catch (AuthenticationException e) {
            token.clear();
            responseType.setRespMsg("用户或密码不正确！");
            return responseType;
        }catch (Exception e){
            if(responseType.isStatus()){
                IUser user = sysUserService.getUserByLoginName(iUser.getIuLname());
                responseType.setData(JwtUtils.createTokenWithClaim(new User(user.getIuId(),user.getIuLname())));
            }
            return responseType;
        }

    }

}
